package cn.layku.service.member.controller;

import cn.hutool.core.map.MapUtil;
import cn.layku.service.member.service.MemberService;
import cn.layku.service.member.util.ApiResult;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class MemberController {

    @Resource(name = "memberService")
    private MemberService memberService;

    /**
     * 添加
     */
    @PostMapping("/member/add")
    public ApiResult<Object> add(@RequestParam Map<String, Object> map) {
        int i = memberService.add(map);
        if (i > 0) {
            return ApiResult.successResult();
        }
        return ApiResult.failResult("添加会员失败");
    }

    /**
     * 修改
     */
    @PostMapping("/member/update")
    public ApiResult<Object> update(@RequestParam Map<String, Object> map) {
        Integer score = MapUtil.getInt(map, "score");
        if (score > 100) {
            try {
                //手工回滚事务
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ApiResult.failResult("订单积分异常");
        }
        int i = memberService.update(map);
        if (i > 0) {
            return ApiResult.successResult();
        }
        return ApiResult.failResult("修改会员失败");
    }

    /**
     * 获取
     */
    @PostMapping("/member/get")
    public ApiResult<Map<String, Object>> get(@RequestParam("memberId") Integer memberId) {
        Map<String, Object> data = memberService.get(memberId);
        if (data != null) {
            return ApiResult.successResultForData(data);
        }
        return ApiResult.failResult("获取会员信息失败");
    }

}
